import json
import os
import sys
from nameko.rpc import rpc

sys.path.append("../")

from utils import dbutil,Utils
from config import Config

class Model:
    name = "model_management"

    @rpc
    def create_model(self,user_id,model_name):
        """
        创建模型
        :param model_name:
        :return:
        """
        model_path = Config.model_file_path.replace("user_id",user_id)  # 指定用户的所有model的存储路径
        if not os.path.exists(model_path):
            os.makedirs(model_path)  # 多层创建目录
        model_file_path = os.path.join(model_path, model_name)
        if os.path.exists(model_file_path):
            msg = "模型已存在"
            status = 403
        else:
            try:
                os.makedirs(model_file_path)
                sql = r"""
                        insert into app_model(user_id,model_name,create_time,status,model_path)
                        values ('{}','{}',now(),'{}',{})
                        """.format(user_id, model_name, 'untrained',repr(model_file_path))
                dbutil.insert(sql)
                msg = '模型创建成功'
                status = 200
            except:
                msg = '模型创建失败'
                status = 500
                if os.path.exists(model_file_path):
                    Utils.del_dir(model_file_path)
        respond = {
            'msg':msg,
            'status':status
        }

        return respond

    @rpc
    def get_model(self, user_id, model_name):
        """
        获取模型信息
        :param model_name:
        :return:
        """
        try:
            sql = """
                select * from app_model
                where user_id='{}' and model_name = '{}'
            """.format(user_id, model_name)

            result = dbutil.query(sql)
            print("-------",result)

            if result:
                temp = {}
                i = 0
                # 0 id;1:user_id;2:model_name;
                temp["user_id"] = result[i][1]
                temp["model_name"] = result[i][2]
                temp["create_time"] = result[i][4].strftime("%Y-%m-%d %H:%M:%S")  # 4 create_time
                temp["dataset_name"] = result[i][3] if result[i][3] != None else '无'  # dataset_name
                temp["learnning rate"] = result[i][12] if result[i][12] != None else -1  # learnning rate
                temp["batch_size"] = result[i][11] if result[i][11] != None else -1  # batch_size
                temp["train_start_time"] = result[i][5].strftime("%Y-%m-%d %H:%M:%S") if result[i][5] != None else '无'  # 训练开始时间
                temp["train_end_time"] = result[i][6].strftime("%Y-%m-%d %H:%M:%S") if result[i][6] != None else '无'  # 结束时间
                temp["status"] = result[i][7]  # 7 status
                # temp["loss"] = result[i][13] if result[i][13] != None else -1  # loss
                temp["ROUGE-1"] = result[i][14] if result[i][14] != None else -1  # ROUGE-1
                temp["ROUGE-2"] = result[i][10] if result[i][10] != None else -1  # ROUGE-2
                temp["ROUGE-L"] = result[i][13] if result[i][13] != None else -1  # ROUGE-L
                respond = {
                    "msg": "success",
                    'status': 200,
                    'data': temp
                }
            else:
                respond={
                    "msg": "模型不存在",
                    'status': 404,
                }
        except:
            respond = {
                "msg": "程序执行出错",
                'status': 500,
            }

        return json.dumps(respond)

    @rpc
    def get_model_list(self,user_id):
        """
        获取模型信息列表
        :return:
        """

        sql = """
            select * from app_model where user_id={}
        """.format(user_id)
        result = dbutil.query(sql)
        if result:
            result = list(result)
            result_list = []
            for i, item in enumerate(result):
                temp = {}
                # 0 id;1:user_id;2:model_name;
                temp["user_id"] = result[i][1]
                temp["model_name"] = result[i][2]
                temp["create_time"] = result[i][4].strftime("%Y-%m-%d %H:%M:%S")  # 4 create_time
                temp["dataset_name"] = result[i][3] if result[i][3] != None else '无'   # dataset_name
                temp["learnning rate"] = result[i][12] if result[i][12] != None else -1     # learnning rate
                temp["batch_size"] = result[i][11] if result[i][11] != None else -1  # batch_size
                temp["train_start_time"] = result[i][5].strftime("%Y-%m-%d %H:%M:%S") if result[i][5] != None else '无'  # 训练开始时间
                temp["train_end_time"] = result[i][6].strftime("%Y-%m-%d %H:%M:%S") if result[i][6] != None else '无'  # 结束时间
                temp["status"] = result[i][7]  # 7 status
                # temp["loss"] = result[i][13] if result[i][13]!=None else -1  # loss
                temp["ROUGE-1"] = result[i][14] if result[i][14] != None else -1  # ROUGE-1
                temp["ROUGE-2"] = result[i][10] if result[i][10] != None else -1  # ROUGE-2
                temp["ROUGE-L"] = result[i][13] if result[i][13] != None else -1  # ROUGE-L
                result_list.append(temp)
            result = {
                'msg': "success",
                'status': 200,
                'data': result_list
            }
        else:
            result = {
                'msg': "用户不存在或此用户无模型",
                'status': 404,
            }

        return json.dumps(result)

    @rpc
    def del_model(self, user_id, model_name):
        """
        删除模型
        :param user_id: 
        :param model_name: 
        :return: 
        """
        sql = """
                select model_path from app_model
                where user_id='{}' and model_name='{}'
            """.format(user_id, model_name)
        result = dbutil.query(sql)
        if result:
            # 删除数据库记录
            sql = """
                    delete from app_model where user_id='{}' and model_name = '{}'
                """.format(user_id, model_name)
            dbutil.delete(sql)
            # 删除存放对应模型得文件夹
            model_path = result[0][0]
            model_dir_path = os.path.join(model_path, '')
            Utils.del_dir(model_dir_path)
            msg = "success"
            status = 200
        else:
            msg = "模型{}不存在".format(model_name)
            status = 404
        result = {
            'msg': msg,
            'status': status
        }
        return json.dumps(result)